var api_url = 'http://localhost:1609';

var ws_url = 'ws://localhost:1609';

var token = '';

export var user = {
	'userid': 0,
	'username': '',
	'realname': '',
	'role': 'student',
	'avatar': '',
	'birthday': '1970-01-01',
	'gender': 0
};

export function init() {
	token = uni.getStorageSync('token');
	if (token == undefined || token == null) {
		token = '';
	}
	var url = uni.getStorageSync('url');
	if (url == undefined || url == null) {
		url = 'localhost:1609';
	}
	api_url = 'http://' + url;
	ws_url = 'ws://' + url;
}

export function loadUserInfo(success, complete) {
	getSync('/api/user/current', {},
		res => {
			if (res.code == 200 && res.data != undefined && res.data != null) {
				user.userid = res.data.id;
				user.username = res.data.userName;
				user.realname = res.data.realName;
				user.role = res.data.role;
				user.avatar = res.data.avatar;
				user.birthday = res.data.birthday;
				user.gender = res.data.gender;
				success(user);
			}
			complete();
		},
		error => {
			complete();
		});
};

export function isLoggedIn() {
	return token != undefined && token != '';
}

export function getUrl() {
	let url = uni.getStorageSync('url');
	if (url == undefined || url == null) {
		url = 'localhost:1609';
	}
	return url;
}

export function updateUrl(url) {
	uni.setStorageSync('url', url);
	api_url = 'http://' + url;
	ws_url = 'ws://' + url;
}

export function updateToken(input) {
	token = input;
	saveToken();
}

export function saveToken() {
	uni.setStorageSync('token', token);
}

export function getSync(path, body, funSuccess, funFail) {
	request(path, body, funSuccess, funFail, false, 'GET');
}

export function getAsync(path, body, funSuccess, funFail) {
	request(path, body, funSuccess, funFail, true, 'GET');
}

export function postSync(path, body, funSuccess, funFail) {
	request(path, body, funSuccess, funFail, false, 'POST');
}

export function postAsync(path, body, funSuccess, funFail) {
	request(path, body, funSuccess, funFail, true, 'POST');
}

function request(path, body, funSuccess, funFail, isAsync, type) {
	uni.request({
		url: api_url + path,
		data: body,
		header: {
			'Access-Token': token,
			'Content-Type': 'application/json'
		},
		async: isAsync,
		method: type,
		success: function(res) {
			if (res.code == 402) {
				uni.showToast({
					title: '身份过期',
					icon: 'error',
					duration: 2000
				});
				updateToken('');
				saveToken();
				uni.redirectTo({
					url: '/pages/index/index'
				})
				return;
			}
			funSuccess(res.data);
		},
		fail: function(err) {
			funFail(err);
		}
	});
};

export function uploadFile(url, path, funSuccess, funFail) {
	uni.uploadFile({
		url: api_url + url,
		name: 'file',
		filePath: path,
		header: {
			'Access-Token': token
		},
		async: true,
		success: function(res) {
			funSuccess(res);
		},
		fail: function(err) {
			funFail(err);
		}
	})
}

var webSocket = null;

var receiveMsgCallback = null;

var onMessage = null;

export function connectWebSocket() {
	uni.closeSocket();
	if (token == undefined || token == null || token == '') {
		return;
	}
	uni.connectSocket({
		url: ws_url + '/ws/message/' + token
	});
	uni.onSocketOpen(function (res) {
	  console.log('WebSocket 连接已打开！');
	});
	uni.onSocketError(function (res) {
	  console.log('WebSocket 连接打开失败，请检查！');
	});
	uni.onSocketClose(function (res) {
	  console.log('WebSocket 已关闭！');
	});
	uni.onSocketMessage((res) => {
		var msg = JSON.parse(res.data);
		if (receiveMsgCallback) {
			try {
				receiveMsgCallback(msg);
			} catch (err) {
				console.log(err)
			}
		}
		if (onMessage) {
			try {
				onMessage(msg);
			} catch (err) {
				console.log(err)
			}
		}
	});
}

export function onReceiveMsgCallback(func) {
	receiveMsgCallback = func;
}

export function listenMessage(func) {
	onMessage = func;
}